<?php


namespace app\service;


use app\entity\SysRoleEntity;
use app\entity\SysRoleMenuEntity;
use app\models\request\ReqRoleList;
use app\models\request\ReqRoleUpdate;
use app\models\response\RespRoleDetail;
use app\models\response\RespRoleList;
use yii\data\Pagination;

class SysRoleService
{
    public function findList() {
        $list = SysRoleEntity::find()->orderBy("create_time desc")->all();
        if (!$list) return $list;
        $arr = [];
        foreach ($list as $row) {
            $d = new RespRoleDetail();
            $d->setRoleName($row->role_name);
            $d->setRoleId($row->role_id);
            $arr[] = $d;
        }
        return $arr;
    }

    public function queryPage(ReqRoleList $req) {

        $data = SysRoleEntity::find()->orderBy("create_time asc");
        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => $req->getPageSize(),'page'=>$req->getPageNum()-1]);
        /**@var $entities SysRoleEntity[]*/
        $entities = $data->offset($pages->getOffset())->limit($pages->getLimit())->all();



        $resp =  new RespRoleList();
        $arr = [];
        foreach ($entities as $row) {


            $d = new RespRoleDetail();
            $d->setRoleName($row->getRoleName());
            $d->setRoleId($row->getRoleId());
            $menuList = SysRoleMenuEntity::find()->where(["role_id"=>$d->getRoleId()])->all();
            $idList = [];
            if ($menuList) {
                foreach ($menuList as $menu) {
                    $idList[] = (string)$menu->menu_id;
                }
            }
            $d->setMenuIdList($idList);
            $arr[] = $d;

        }
        $resp->setList($arr);
        $resp->setPageSize($req->getPageSize());
        $resp->setTotal(intval($pages->totalCount));


        return $resp;
    }

    public function update(ReqRoleUpdate $req) {
        if ($req->getRoleId()) {
            $entity = SysRoleEntity::find()->where(["role_id"=>$req->getRoleId()])->one();
        } else {
            $entity = new SysRoleEntity();
        }
        $entity->setCreateUserId($req->getCreateUserId());
        $entity->setRoleName($req->getRoleName());
        $entity->save($entity);
        $roleId = $entity->primaryKey;
        $service = new SysRoleMenuService();
        $service->saveOrUpdate($roleId,$req->getMenuIdList());
        return true;
    }

    public  function  deleteBatch($roleIds){
        SysRoleEntity::deleteAll(['in', 'role_id', $roleIds]);
        return true;
    }
}